<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch && !hideUI"
      label-width="68px">
      <!-- 添加校区搜索条件 -->
      <el-form-item label="校区" prop="cellId">
        <el-select v-model="queryParams.cellId" placeholder="请选择校区" clearable @change="handleQueryCellChange">
          <el-option v-for="item in cellOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <!-- 添加楼栋搜索条件 -->
      <el-form-item label="楼栋" prop="unitId">
        <el-select v-model="queryParams.unitId" placeholder="请选择楼栋" clearable @change="handleQueryUnitChange"
          :disabled="!queryParams.cellId">
          <el-option v-for="item in unitOptions" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>

      <!-- 添加楼层搜索条件 -->
      <el-form-item label="楼层" prop="floorId">
        <el-select v-model="queryParams.floorId" placeholder="请选择楼层" clearable @change="handleQueryFloorChange"
          :disabled="!queryParams.unitId">
          <el-option v-for="item in floorOptions" :key="item.id" :label="item.floorName" :value="item.id" />
        </el-select>
      </el-form-item>

      <!-- 添加房间搜索条件 -->
      <el-form-item label="房间" prop="homeId">
        <el-select v-model="queryParams.homeId" placeholder="请选择房间" clearable :disabled="!queryParams.floorId">
          <el-option v-for="item in homeOptions" :key="item.id" :label="item.roomName" :value="item.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="姓名" prop="tenantName">
        <el-input v-model="queryParams.tenantName" placeholder="请输入住户姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="学工号" prop="idCardNumber">
        <el-input v-model="queryParams.idCardNumber" placeholder="请输学工号" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <!-- <el-form-item label="关系" prop="relation">
        <el-select v-model="queryParams.relation" placeholder="请选择关系" clearable>
          <el-option
            v-for="dict in dict.type.relation"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item> -->

      <el-form-item label="操作状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择操作状态" clearable>
          <el-option v-for="dict in dict.type.is_effectiveness" :key="dict.value" :label="dict.label"
            :value="dict.value" />
        </el-select>
      </el-form-item>

      <!--  <el-form-item label="到期状态" prop="expiryStatus">
        <el-select v-model="queryParams.expiryStatus" placeholder="请选择到期状态" clearable>
          <el-option label="已到期" value="expired" />
          <el-option label="即将到期" value="expiring" />
          <el-option label="有效期内" value="valid" />
        </el-select>
      </el-form-item> -->

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8" v-if="!hideUI">
      <el-col :span="1.5">
        <!-- 新增按钮暂时注释掉 -->
        <!--<el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['lock:tenantkey:add']"
        >新增</el-button>-->
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['lock:tenantkey:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['lock:tenantkey:remove']"
        >删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport"
          v-hasPermi="['lock:tenantkey:export']">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="tenantkeyList" @selection-change="handleSelectionChange" :max-height="hideUI ? '500' : undefined">
      <!-- <el-table-column type="selection" width="55" align="center" /> -->
      <!-- <el-table-column v-if="!hideUI" label="MAC" align="center" prop="mac"  /> -->
      <el-table-column v-if="!hideUI" label="房间" align="center">
        <template slot-scope="scope">
          {{ scope.row.cellName || '' }} {{ scope.row.unitName || '' }} {{ scope.row.floorName || '' }}
          {{ scope.row.roomName || '' }}
        </template>
      </el-table-column>
      <el-table-column label="姓名" align="center" prop="tenantName" />
      <el-table-column label="学工号" align="center" prop="idCardNumber" />
      <!-- <el-table-column label="学工号" align="center" prop="idCardNumber" v-if="!hideUI"/> -->
      <!-- <el-table-column label="住户名" align="center" prop="userName" /> -->
      <!-- <el-table-column label="住户电话" align="center" prop="userPhone" /> -->
      <!--  <el-table-column label="关系" align="center" prop="relation">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.relation" :value="scope.row.relation"/>
        </template>
      </el-table-column> -->
      <el-table-column label="类别" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.key_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="秘钥" align="center" prop="password" />
      <el-table-column label="有效期" align="center" width="220">
        <template slot-scope="scope">
          <span v-if="scope.row.startTime || scope.row.endTime">
            {{ scope.row.startTime ? parseTime(scope.row.startTime, '{y}-{m}-{d}') : '无起始' }} 至
            {{ scope.row.endTime ? parseTime(scope.row.endTime, '{y}-{m}-{d}') : '无截止' }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column> -->
      <!--      <el-table-column label="距离到期" align="center" width="100">
        <template slot-scope="scope">
          <span v-if="scope.row.endTime" :class="getRemainingDaysClass(scope.row.endTime)">
            {{ getRemainingDaysText(scope.row.endTime) }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column> -->
      <el-table-column label="生效" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.is_effectiveness" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="冻结状态" align="center" prop="isItAvailable">
        <template slot-scope="scope">
          <span v-if="scope.row.flgDelete == 0">已删除</span>
          <dict-tag v-else :options="dict.type.freeze_status_type" :value="scope.row.isItAvailable" />

        </template>
      </el-table-column>

      <el-table-column label="删除标识" align="center" prop="flgDelete">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.delete_flg_type" :value="scope.row.flgDelete" />
        </template>
      </el-table-column>
      <!-- <el-table-column label="钥匙授权" align="center" prop="isKeyRz">
        <template slot-scope="scope">
          <el-tag :type="scope.row.isKeyRz == 1 ? 'success' : 'info'">
            {{ scope.row.isKeyRz == 1 ? '已授权' : '未授权' }}
          </el-tag>
        </template>
      </el-table-column> -->
      <!-- 卡号字段暂时注释掉 -->
      <!-- <el-table-column label="备注" align="center" prop="remark" /> -->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <!-- 删除详情按钮 -->
          <el-button size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"
            v-hasPermi="['lock:tenantkey:query']">详情</el-button>
          <!--      <el-button
            size="mini"
            type="text"
            icon="el-icon-date"
            @click="handlePasswordUpdate(scope.row)"
            v-if="scope.row.flgDelete == 1 && scope.row.type === '1'"
            :disabled="isNotAuthorized(scope.row)"
            :class="{'button-disabled': isNotAuthorized(scope.row)}"
            v-tooltip="{content: isNotAuthorized(scope.row) ? '钥匙未授权，不能修改密码' : '', placement: 'top'}"
            v-hasPermi="['lock:tenantkey:edit']"
          >修改密码</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleRenew(scope.row)"
            v-if="scope.row.flgDelete == 1"
            :disabled="isNotAuthorized(scope.row)"
            :class="{'button-disabled': isNotAuthorized(scope.row)}"
            v-tooltip="{content: isNotAuthorized(scope.row) ? '钥匙未授权，不能续期' : '', placement: 'top'}"
            v-hasPermi="['lock:tenantkey:edit']"
          >续期</el-button>
          <el-button
            size="mini"
            type="text"
            :icon="scope.row.isItAvailable == 1 ? 'el-icon-unlock' : 'el-icon-lock'"
            @click="toggleFreeze(scope.row)"
            v-if="scope.row.flgDelete == 1"
            :disabled="isNotAuthorized(scope.row)"
            :class="{'button-disabled': isNotAuthorized(scope.row)}"
            v-tooltip="{content: isNotAuthorized(scope.row) ? '钥匙未授权，不能冻结/解冻' : '', placement: 'top'}"
            v-hasPermi="['lock:tenantkey:edit']"
          >{{ scope.row.isItAvailable == 1 ? '解冻' : '冻结' }}</el-button> -->
          <el-button size="mini" type="text" :disabled="!scope.row.pwdId" :class="{'button-disabled': !scope.row.pwdId}"
            v-if="scope.row.flgDelete == 1" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['lock:tenantkey:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 详情弹出层 -->
    <el-dialog :visible.sync="open" title="钥匙详情" width="70%" custom-class="detail-dialog">
      <div class="detail-container">
        <!-- 标题区域 -->
        <div class="detail-header">

          <div class="location-info">
            <i class="el-icon-location"></i>
            <span>{{ (form.cellName || '') + ' ' + (form.unitName || '') + ' ' + (form.floorName || '') + ' ' + (form.roomName || '') }}</span>
          </div>
          <!--   <div :class="['key-status', {'key-status-active': form.isKeyRz == 1, 'key-status-inactive': form.isKeyRz != 1}]">
            {{ form.isKeyRz == 1 ? '已授权' : '未授权' }}
          </div> -->
        </div>

        <el-divider content-position="left">
          <i class="el-icon-house"></i> 钥匙信息
        </el-divider>

        <div class="detail-section resident-section">
          <el-row :gutter="20">
            <!--   <el-col :span="8">
              <div class="detail-item">
                <span class="detail-label"><i class="el-icon-mobile-phone"></i> 住户电话</span>
                <span class="detail-value">{{ form.userPhone || '-' }}</span>
              </div>
            </el-col> -->
            <!--         <el-col :span="8">
              <div class="detail-item">
                <span class="detail-label"><i class="el-icon-connection"></i> 关系</span>
                <span class="detail-value">
                  <dict-tag :options="dict.type.relation" :value="form.relation"/>
                </span>
              </div>
            </el-col> -->
          </el-row>

          <el-row :gutter="20" class="mt10">
            <el-col :span="8">
              <div class="detail-item">
                <span class="detail-label"><i class="el-icon-wallet"></i> 钥匙类别</span>
                <span class="detail-value">
                  <dict-tag :options="dict.type.key_type" :value="form.type" />
                </span>
              </div>
            </el-col>
              <el-col :span="8" v-if="form.type==1">
              <div class="detail-item">
                <span class="detail-label"><i class="el-icon-lock"></i> 秘钥</span>
                <span class="detail-value">{{ form.password || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <span class="detail-label"><i class="el-icon-time"></i> 有效期</span>
                <span class="detail-value">
                  {{ form.startTime ? parseTime(form.startTime, '{y}-{m}-{d}') : '-' }} 至
                  {{ form.endTime ? parseTime(form.endTime, '{y}-{m}-{d}') : '-' }}
                </span>
              </div>
            </el-col>
          </el-row>

          <el-row :gutter="20" class="mt10">
            <el-col :span="8">
              <div class="detail-item">
                <span class="detail-label"><i class="el-icon-timer"></i> 剩余时间</span>
                <span class="detail-value" :class="getRemainingDaysClass(form.endTime)">
                  {{ form.endTime ? getRemainingDaysText(form.endTime) : '-' }}
                </span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <span class="detail-label"><i class="el-icon-connection"></i> 状态</span>
                <span class="detail-value">
                  <dict-tag :options="dict.type.is_effectiveness" :value="form.status" />
                </span>
              </div>
            </el-col>
            <!--      <el-col :span="8">
              <div class="detail-item">
                <span class="detail-label"><i class="el-icon-unlock"></i> 冻结状态</span>
                <span class="detail-value">
                  <dict-tag :options="dict.type.freeze_status_type" :value="form.isItAvailable"/>
                </span>
              </div>
            </el-col> -->
          </el-row>
        </div>

        <el-divider content-position="left">
          <i class="el-icon-user"></i> 人员信息
        </el-divider>

        <div class="detail-section tenant-section">
          <el-row :gutter="20">
            <el-col :span="8">
              <div class="detail-item">
                <span class="detail-label"><i class="el-icon-user"></i> 人员姓名</span>
                <span class="detail-value">{{ form.tenantName || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8" v-if="form.type==2">
              <div class="detail-item">
                <span class="detail-label"><i class="el-icon-mobile-phone"></i> 卡号</span>
                <span class="detail-value">{{ form.cardNo || '-' }}</span>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="detail-item">
                <span class="detail-label"><i class="el-icon-document"></i> 学工号</span>
                <span class="detail-value">{{ form.idCardNumber || '-' }}</span>
              </div>
            </el-col>
          </el-row>
        </div>

        <el-divider content-position="left">
          <i class="el-icon-document"></i> 备注信息
        </el-divider>

        <div class="detail-section remark-section">
          <div class="detail-item">
            <span class="detail-value full-width">{{ form.remark || '暂无备注' }}</span>
          </div>
        </div>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancel">关闭</el-button>
      </span>
    </el-dialog>

    <!-- 修改密码弹出层 -->
    <el-dialog :visible.sync="passwordOpen" title="修改密码" width="400px">
      <el-form :model="passwordForm" ref="passwordForm" :rules="passwordRules" label-width="70px">
        <el-form-item label="密码" prop="password">
          <el-input v-model="passwordForm.password" type="text" placeholder="请输入6位数字密码"></el-input>
          <div class="form-tip">
            <i class="el-icon-info"></i> 密码必须是6位数字且不能以0开头
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelPassword">取消</el-button>
        <el-button type="primary" @click="submitPasswordForm">提交</el-button>
      </span>
    </el-dialog>

    <!-- 续租弹出层 -->
    <el-dialog :visible.sync="renewOpen" title="续期" width="450px">
      <el-form :model="renewForm" ref="renewForm" :rules="renewRules" label-width="80px">
        <el-form-item label="开始时间" prop="startTime">
          <el-date-picker v-model="renewForm.startTime" type="datetime" placeholder="选择开始日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          <div class="form-tip">
            <i class="el-icon-info"></i> 钥匙开始生效日期时间，请精确到时分秒
          </div>
        </el-form-item>
        <el-form-item label="结束时间" prop="endTime">
          <el-date-picker v-model="renewForm.endTime" type="datetime" placeholder="选择结束日期时间"
            value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          <div class="form-tip">
            <i class="el-icon-info"></i> 钥匙到期日期时间，不能早于开始时间，请精确到时分秒
          </div>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="cancelRenew">取消</el-button>
        <el-button type="primary" @click="submitRenewForm">提交</el-button>
      </span>
    </el-dialog>

    <!-- 合同对话框 -->
    <!-- <contract-dialog
      :visible.sync="contractDialogVisible"
      :title="contractTitle"
      :formData="contractForm"
      @refresh="getList"
    /> -->
  </div>
</template>

<script>
  import {
    listTenantkey,
    getTenantkey,
    delTenantkey,
    updateTenantkey,
    freezePwd,
    freezeCard,
    updateDate,
    updateKey
  } from "@/api/lock/tenantkey";
  // 添加位置相关的API导入
  import {
    listCell2
  } from "@/api/lock/cell";
  import {
    listUnit2
  } from "@/api/lock/unit";
  import {
    listFloor2
  } from "@/api/lock/floor";
  import {
    listHome2
  } from "@/api/lock/home";
  // 移除合同相关API导入
  // import { listContract, getContract } from "@/api/lock/contract";
  // 移除合同对话框组件导入
  // import ContractDialog from "@/views/lock/contract/components/ContractDialog";

  export default {
    name: "Tenantkey",
    props: {
      homeId: {
        type: [String, Number],
        default: null
      },
      hideUI: {
        type: Boolean,
        default: false
      }
    },
    // 移除合同对话框组件
    // components: {
    //   ContractDialog
    // },
    dicts: ['is_effectiveness', 'key_type', 'delete_flg_type', 'freeze_status_type', 'contract_type',
      'contract_status'],
    data() {
      // 创建一个验证结束日期的函数
      const validateEndDate = (rule, value, callback) => {
        if (value && this.renewForm.startTime) {
          const startDate = new Date(this.renewForm.startTime);
          const endDate = new Date(value);
          if (endDate < startDate) {
            callback(new Error('结束时间不能早于开始时间'));
          } else {
            callback();
          }
        } else {
          callback();
        }
      };

      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 人员钥匙表格数据
        tenantkeyList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 密码弹出层
        passwordOpen: false,
        // 续租弹出层
        renewOpen: false,
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          mac: null,
          idCardNumber: null,
          userPhone: null,
          relation: null,
          status: null,
          expiryStatus: null,
          homeId: null
        },
        // 表单参数
        form: {},
        // 密码表单
        passwordForm: {},
        // 续租表单
        renewForm: {},
        // 表单校验
        rules: {
          mac: [{
            required: true,
            message: "MAC不能为空",
            trigger: "blur"
          }],
          cellId: [{
            required: true,
            message: "校区ID不能为空",
            trigger: "blur"
          }],
          floorId: [{
            required: true,
            message: "楼层ID不能为空",
            trigger: "blur"
          }],
          unitId: [{
            required: true,
            message: "楼栋ID不能为空",
            trigger: "blur"
          }],
          homeId: [{
            required: true,
            message: "房间ID不能为空",
            trigger: "blur"
          }],
          type: [{
            required: true,
            message: "类别不能为空",
            trigger: "change"
          }],
          password: [{
              required: true,
              message: "秘钥不能为空",
              trigger: "blur"
            },
            {
              min: 6,
              max: 6,
              message: "密码必须是6位",
              trigger: "blur"
            },
            {
              pattern: /^[1-9]\d{5}$/,
              message: "密码必须是6位数字且不能以0开头",
              trigger: "blur"
            },
            {
              validator: (rule, value, callback) => {
                // 检查是否是连续的数字序列，如123456或654321
                if (value) {
                  let isConsecutive = true;
                  for (let i = 0; i < value.length - 1; i++) {
                    if (Math.abs(parseInt(value[i]) - parseInt(value[i + 1])) !== 1) {
                      isConsecutive = false;
                      break;
                    }
                  }
                  if (isConsecutive) {
                    callback(new Error("密码不能是连续的数字序列，如123456或654321"));
                  } else {
                    callback();
                  }
                } else {
                  callback();
                }
              },
              trigger: "blur"
            }
          ],
          startTime: [{
            required: true,
            message: "开始时间不能为空",
            trigger: "change"
          }],
          endTime: [{
            required: true,
            message: "结束时间不能为空",
            trigger: "change"
          }],
          status: [{
            required: true,
            message: "状态不能为空",
            trigger: "change"
          }],
          isItAvailable: [{
            required: true,
            message: "冻结状态不能为空",
            trigger: "change"
          }],
          cardNo: [{
            required: true,
            message: "卡号不能为空",
            trigger: "blur"
          }]
        },
        // 密码表单校验
        passwordRules: {
          password: [{
              required: true,
              message: "秘钥不能为空",
              trigger: "blur"
            },
            {
              min: 6,
              max: 6,
              message: "密码必须是6位",
              trigger: "blur"
            },
            {
              pattern: /^[1-9]\d{5}$/,
              message: "密码必须是6位数字且不能以0开头",
              trigger: "blur"
            },
            {
              validator: (rule, value, callback) => {
                // 检查是否是连续的数字序列，如123456或654321
                if (value) {
                  let isConsecutive = true;
                  for (let i = 0; i < value.length - 1; i++) {
                    if (Math.abs(parseInt(value[i]) - parseInt(value[i + 1])) !== 1) {
                      isConsecutive = false;
                      break;
                    }
                  }
                  if (isConsecutive) {
                    callback(new Error("密码不能是连续的数字序列，如123456或654321"));
                  } else {
                    callback();
                  }
                } else {
                  callback();
                }
              },
              trigger: "blur"
            }
          ]
        },
        // 续租表单校验
        renewRules: {
          startTime: [{
            required: true,
            message: "开始时间不能为空",
            trigger: "change"
          }],
          endTime: [{
              required: true,
              message: "结束时间不能为空",
              trigger: "change"
            },
            {
              validator: validateEndDate,
              trigger: "change"
            }
          ]
        },

        // 是否是详情查看
        isDetail: false,
        // 是否嵌入
        isEmbedded: false,

        // 添加位置选项数据
        cellOptions: [],
        unitOptions: [],
        floorOptions: [],
        homeOptions: [],
      };
    },
    created() {
      // 先加载校区数据
      this.getCellList().then(() => {
        // 如果传入了homeId，则设置为嵌入模式
        if (this.homeId) {
          this.queryParams.homeId = this.homeId;
          this.isEmbedded = true;
        }

        // 从路由参数中获取过滤条件
        const waringType = this.$route.query.waringType;
        if (waringType !== undefined) {
          // 设置到期状态下拉框的值
          switch (waringType) {
            case '2':
              this.queryParams.expiryStatus = 'expired';
              break;
            case '1':
              this.queryParams.expiryStatus = 'expiring';
              break;
            case '0':
              this.queryParams.expiryStatus = 'valid';
              break;
          }
        }

        this.getList();
      });
    },
    methods: {
      /** 判断钥匙是否未授权 */
      isNotAuthorized(row) {
        // 处理可能的字符串和数字类型，以及undefined情况
        return row.isKeyRz === 0 || row.isKeyRz === '0' || !row.pwdId;
      },

      /** 获取校区列表 */
      getCellList() {
        return listCell2().then(response => {
          this.cellOptions = response.rows;
        });
      },

      /** 获取楼栋列表 */
      getUnitList(cellId) {
        if (!cellId) {
          this.unitOptions = [];
          return Promise.resolve();
        }

        return listUnit2({
          cellId: cellId
        }).then(response => {
          this.unitOptions = response.rows || [];
        });
      },

      /** 获取楼层列表 */
      getFloorList(unitId) {
        if (!unitId) {
          this.floorOptions = [];
          return Promise.resolve();
        }

        return listFloor2({
          unitId: unitId
        }).then(response => {
          this.floorOptions = response.rows || [];
        });
      },

      /** 获取房间列表 */
      getRoomList(floorId) {
        if (!floorId) {
          this.homeOptions = [];
          return Promise.resolve();
        }

        return listHome2({
          floorId: floorId
        }).then(response => {
          this.homeOptions = response.rows || [];
        });
      },

      /** 搜索条件校区选择改变时触发 */
      handleQueryCellChange(value) {
        if (!value) {
          this.queryParams.unitId = undefined;
          this.queryParams.floorId = undefined;
          this.queryParams.homeId = undefined;
          this.unitOptions = [];
          this.floorOptions = [];
          this.homeOptions = [];
          return;
        }
        this.getUnitList(value);
      },

      /** 搜索条件楼栋选择改变时触发 */
      handleQueryUnitChange(value) {
        if (!value) {
          this.queryParams.floorId = undefined;
          this.queryParams.homeId = undefined;
          this.floorOptions = [];
          this.homeOptions = [];
          return;
        }
        this.getFloorList(value);
      },

      /** 搜索条件楼层选择改变时触发 */
      handleQueryFloorChange(value) {
        if (!value) {
          this.queryParams.homeId = undefined;
          this.homeOptions = [];
          return;
        }
        this.getRoomList(value);
      },

      /** 计算剩余天数 */
      getRemainingDays(endDateStr) {
        if (!endDateStr) return -1;

        const endDate = new Date(endDateStr);
        const today = new Date();
        today.setHours(0, 0, 0, 0);

        // 计算相差的毫秒数
        const diffTime = endDate.getTime() - today.getTime();
        // 转换为天数并向下取整
        const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

        return diffDays;
      },

      /** 获取剩余天数文本 */
      getRemainingDaysText(endDateStr) {
        const days = this.getRemainingDays(endDateStr);

        if (days < 0) {
          return "已过期";
        } else if (days === 0) {
          return "今日到期";
        } else {
          return `剩余${days}天`;
        }
      },

      /** 获取剩余天数样式 */
      getRemainingDaysClass(endDateStr) {
        const days = this.getRemainingDays(endDateStr);

        if (days < 0) {
          return "text-danger";
        } else if (days <= 3) {
          return "text-warning";
        } else {
          return "text-success";
        }
      },
      /** 查询人员钥匙列表 */
      getList() {
        console.log('钥匙管理页面开始加载数据，homeId:', this.homeId);
        this.loading = true;
        // 确保每次查询都使用最新的homeId
        if (this.homeId) {
          this.queryParams.homeId = this.homeId;
        }
        listTenantkey(this.queryParams).then(response => {
          console.log('钥匙管理页面数据加载成功:', response);
          this.tenantkeyList = response.rows;
          this.total = response.total;
          this.loading = false;
          console.log('钥匙管理页面数据加载完成，loading状态已关闭');
        }).catch(error => {
          console.error('钥匙管理页面数据加载失败:', error);
          this.loading = false;
        });
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          mac: null,
          cellId: null,
          cellName: null,
          floorId: null,
          floorName: null,
          unitId: null,
          unitName: null,
          homeId: null,
          roomName: null,
          idCardNumber: null,
          type: null,
          startTime: null,
          endTime: null,
          passwordStatus: null,
          password: null,
          cardNo: null,
          isItAvailable: null,
          flgDelete: null,
          uniCode: null,
          remark: null,
          createBy: null,
          createTime: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        // 重置所有查询参数
        this.queryParams = {
          pageNum: 1,
          pageSize: 10,
          mac: null,
          idCardNumber: null,
          userPhone: null,
          relation: null,
          status: null,
          expiryStatus: null,
          homeId: null,
          cellId: null,
          unitId: null,
          floorId: null
        };
        this.handleQuery();
        // 清空选项数据
        this.unitOptions = [];
        this.floorOptions = [];
        this.homeOptions = [];
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length !== 1;
        this.multiple = !selection.length;
      },
      /** 详情按钮操作 */
      handleDetail(row) {
        this.reset();
        this.isDetail = true;
        const id = row.id;

        getTenantkey(id).then(response => {
          console.log("后端返回的钥匙数据:", response.data);
          // 确保类型转换正确
          const type = typeof response.data.type === 'string' ? parseInt(response.data.type) : response.data.type;
          const status = typeof response.data.status === 'string' ? parseInt(response.data.status) : response.data
            .status;
          const isItAvailable = typeof response.data.isItAvailable === 'string' ? parseInt(response.data
            .isItAvailable) : response.data.isItAvailable;

          this.form = {
            ...response.data,
            cellName: response.data.cellName || "",
            floorName: response.data.floorName || "",
            unitName: response.data.unitName || "",
            roomName: response.data.roomName || "",
            type: type,
            status: status,
            isItAvailable: isItAvailable
          };

          this.open = true;
          this.title = "钥匙详情";
        });
      },
      /** 修改密码按钮操作 */
      handlePasswordUpdate(row) {
        console.log("修改密码按钮点击, 原始数据:", row);
        this.passwordForm = {
          id: row.id,
          mac: row.mac,
          cellName: row.cellName || "",
          floorName: row.floorName || "",
          unitName: row.unitName || "",
          roomName: row.roomName || "",
          userName: row.userName || "",
          idCardNumber: row.idCardNumber || "",
          password: row.password || ""
        };
        console.log("设置到密码表单的数据:", this.passwordForm);
        this.passwordOpen = true;
      },
      /** 提交密码修改 */
      submitPasswordForm() {
        this.$refs["passwordForm"].validate(valid => {
          if (valid) {
            const updateData = {
              id: this.passwordForm.id,
              password: this.passwordForm.password
            };
            updateKey(updateData).then(response => {
              this.$modal.msgSuccess("密码修改成功");
              this.passwordOpen = false;
              this.getList();
            });
          }
        });
      },
      /** 续租按钮操作 */
      handleRenew(row) {
        console.log("续租按钮点击, 原始数据:", row);
        this.renewForm = {
          id: row.id,
          mac: row.mac,
          cellName: row.cellName || "",
          floorName: row.floorName || "",
          unitName: row.unitName || "",
          roomName: row.roomName || "",
          userName: row.userName || "",
          idCardNumber: row.idCardNumber || "",
          startTime: row.startTime || "",
          endTime: row.endTime || ""
        };
        console.log("设置到续租表单的数据:", this.renewForm);
        this.renewOpen = true;
      },
      /** 提交续租表单 */
      submitRenewForm() {
        this.$refs["renewForm"].validate(valid => {
          if (valid) {
            const updateData = {
              id: this.renewForm.id,
              startTime: this.renewForm.startTime,
              endTime: this.renewForm.endTime
            };

            updateDate(updateData).then(response => {
              this.$modal.msgSuccess("续期成功");
              this.renewOpen = false;
              this.getList();
            });
          }
        });
      },
      /** 取消密码修改 */
      cancelPassword() {
        this.passwordOpen = false;
        this.passwordForm = {};
      },
      // 取消续租
      cancelRenew() {
        this.renewOpen = false;
        this.renewForm = {};
      },
      /** 冻结/解冻操作 */
      toggleFreeze(row) {
        // 如果是密码类型且没有pwdId，不允许冻结
        if (row.type === '1' && !row.pwdId) {
          this.$modal.msgError("密码ID不存在，无法进行冻结/解冻操作");
          return;
        }

        const newStatus = row.isItAvailable == 1 ? 0 : 1;
        const action = newStatus == 1 ? '冻结' : '解冻';
        this.$modal.confirm(`是否确认${action}钥匙编号为"${row.id}"的数据项？`).then(() => {
          const updateData = {
            id: row.id,
            pwdId: row.pwdId,
            mac: row.mac,
            isItAvailable: newStatus
          };

          // 根据类型选择不同的接口
          const apiCall = row.type === '1' ? freezePwd : freezeCard;

          apiCall(updateData).then(response => {
            this.$modal.msgSuccess(`${action}成功`);
            this.getList();
          });
        }).catch(() => {});
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        const today = new Date();
        const year = today.getFullYear();
        const month = String(today.getMonth() + 1).padStart(2, '0');
        const day = String(today.getDate()).padStart(2, '0');
        this.form.startTime = `${year}-${month}-${day}`;
        this.open = true;
        this.title = "添加钥匙";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        this.isDetail = false;
        const id = row.id || this.ids;
        getTenantkey(id).then(response => {
          console.log("后端返回的钥匙数据:", response.data);
          this.form = {
            ...response.data,
            cellName: response.data.cellName || "",
            floorName: response.data.floorName || "",
            unitName: response.data.unitName || "",
            roomName: response.data.roomName || "",
            type: parseInt(response.data.type),
            status: parseInt(response.data.status),
            isItAvailable: parseInt(response.data.isItAvailable)
          };
          console.log("设置到表单的数据:", this.form);
          this.open = true;
          this.title = "修改钥匙";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateTenantkey(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addTenantkey(this.form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id;
        this.$modal.confirm('是否确认删除钥匙编号为"' + ids + '"的数据项？').then(function() {
          return delTenantkey(ids);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
      },
      /** 导出按钮操作 */
      handleExport() {
        this.download('lock/tenantkey/export', {
          ...this.queryParams
        }, `tenantkey_${new Date().getTime()}.xlsx`);
      },
      /** 合同按钮操作 - 已移除 */
      /*
      handleContract(row) {
        // 根据钥匙相关信息查询合同信息
        this.getContractByTenant(row.idCardNumber, row.homeId).then(response => {
          if (response.data) {
            // 如果有合同数据，则是编辑模式
            this.contractForm = response.data;
            this.contractTitle = "修改合同";
            this.contractInfo = response.data;
          } else {
            // 如果没有合同数据，则是新增模式
            this.contractForm = {
              tenantId: row.id,
              homeId: row.homeId,
              cellId: row.cellId,
              unitId: row.unitId,
              floorId: row.floorId,
              tenantName: row.userName,
              idCardNumber: row.idCardNumber
            };
            this.contractTitle = "新增合同";
            this.contractInfo = null;
          }
          this.contractDialogVisible = true;
        });
      },
      */
      /** 根据人员信息获取合同信息 - 已移除 */
      /*
      getContractByTenant(idCardNumber, homeId) {
        return listContract({
          idCardNumber: idCardNumber,
          homeId: homeId,
          pageSize: 1,
          pageNum: 1
        }).then(response => {
          if (response.rows && response.rows.length > 0) {
            return getContract(response.rows[0].id);
          }
          return { data: null };
        });
      }
      */
    },
    watch: {
      homeId: {
        handler(newVal) {
          this.queryParams.homeId = newVal;
          this.isEmbedded = !!newVal;
          this.getList();
        },
        immediate: true
      },
      '$route.query': {
        handler(newQuery) {
          console.log('钥匙管理页面接收到路由参数:', newQuery);

          // 处理homeId参数
          if (newQuery.homeId !== undefined) {
            console.log('设置homeId:', newQuery.homeId);
            this.homeId = newQuery.homeId;
            this.queryParams.homeId = newQuery.homeId;
            this.isEmbedded = !!newQuery.homeId;
            this.getList();
          }

          // 处理waringType参数
          const waringType = newQuery.waringType;
          if (waringType !== undefined) {
            // 设置到期状态下拉框的值
            switch (waringType) {
              case '2':
                this.queryParams.expiryStatus = 'expired';
                break;
              case '1':
                this.queryParams.expiryStatus = 'expiring';
                break;
              case '0':
                this.queryParams.expiryStatus = 'valid';
                break;
            }
            this.getList();
          }
        },
        immediate: true
      }
    }
  };
</script>

<style scoped>
  .small-padding {
    padding: 0 5px;
  }

  .fixed-width {
    width: 150px;
  }

  /* 过期显示红色 */
  .text-danger {
    color: #f56c6c;
    font-weight: bold;
  }

  /* 即将过期显示黄色 */
  .text-warning {
    color: #e6a23c;
    font-weight: bold;
  }

  /* 有效期内显示绿色 */
  .text-success {
    color: #67c23a;
    font-weight: bold;
  }

  /* 禁用按钮样式 */
  .button-disabled {
    color: #c0c4cc !important;
    cursor: not-allowed !important;
    opacity: 0.7 !important;
    text-decoration: none !important;
  }

  /* 确保禁用按钮不会被element-ui的hover效果覆盖 */
  .el-button--text.button-disabled:hover,
  .el-button--text.button-disabled:focus,
  .el-button--text.button-disabled:active {
    color: #c0c4cc !important;
    border-color: transparent !important;
    background-color: transparent !important;
  }

  /* 表单提示样式 */
  .form-tip {
    font-size: 12px;
    color: #909399;
    line-height: 1.4;
    margin-top: 5px;
    padding-left: 2px;
  }

  .form-tip i {
    margin-right: 4px;
    color: #E6A23C;
  }

  /* 禁用输入框样式 */
  .disabled-input ::v-deep .el-input__inner {
    background-color: #f5f7fa;
    border-color: #e4e7ed;
    color: #c0c4cc;
    cursor: not-allowed;
  }

  /* 钥匙类型徽章 */
  .key-type-info {
    margin-bottom: 20px;
  }

  .key-type-badge {
    display: inline-block;
    padding: 6px 12px;
    border-radius: 4px;
    font-size: 13px;
    font-weight: bold;
    background-color: #909399;
    color: white;
  }

  .key-type-badge.password-type {
    background-color: #409EFF;
  }

  .key-type-badge.card-type {
    background-color: #67c23a;
  }

  /* 详情弹窗样式 */
  .detail-dialog .el-dialog__body {
    padding: 10px 20px;
  }

  .detail-container {
    padding: 10px;
  }

  .detail-header {
    display: flex;
    align-items: left;
    justify-content: flex-start;
    background: #f5f7fa;
    padding: 15px 20px;
    border-radius: 4px;
    margin-bottom: 20px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .key-info {
    font-size: 18px;
    font-weight: bold;
    display: flex;
    align-items: center;
  }

  .key-info i {
    color: #409EFF;
    margin-right: 8px;
    font-size: 22px;
  }

  .location-info {
    display: flex;
    align-items: center;
    color: #606266;
  }

  .location-info i {
    color: #67c23a;
    margin-right: 8px;
  }

  .key-status {
    padding: 5px 15px;
    border-radius: 15px;
    font-size: 14px;
    font-weight: bold;
  }

  .key-status-active {
    background-color: #67c23a;
    color: white;
  }

  .key-status-inactive {
    background-color: #909399;
    color: white;
  }

  .detail-section {
    margin-bottom: 20px;
    padding: 15px;
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  }

  .tenant-section {
    background-color: #f0f9eb;
    border-left: 4px solid #67c23a;
  }

  .resident-section {
    background-color: #f0f9ff;
    border-left: 4px solid #409EFF;
  }

  .remark-section {
    background-color: #fdf6ec;
    border-left: 4px solid #e6a23c;
  }

  .detail-item {
    margin-bottom: 15px;
    display: flex;
    align-items: center;
  }

  .detail-label {
    color: #606266;
    margin-right: 10px;
    width: 100px;
    display: inline-block;
  }

  .detail-label i {
    margin-right: 5px;
    color: #409EFF;
  }

  .detail-value {
    color: #303133;
    font-weight: 500;
  }

  .detail-value.full-width {
    white-space: pre-wrap;
    word-break: break-all;
    width: 100%;
    min-height: 40px;
    padding: 10px;
    color: #606266;
  }

  .mt10 {
    margin-top: 10px;
  }

  .el-divider__text {
    font-size: 16px;
    font-weight: bold;
    color: #303133;
  }

  .el-divider__text i {
    margin-right: 5px;
    color: #409EFF;
  }
</style>
